# Makefile for Neural Network Processor Scheduler Optimization

CC = gcc
CFLAGS = -Wall -Wextra -O3 -std=c99
LDFLAGS = -lm

# 启用OpenMP并行支持
ifdef OPENMP
    CFLAGS += -fopenmp
    LDFLAGS += -fopenmp
endif

# 调试模式
ifdef DEBUG
    CFLAGS += -g -DDEBUG -O0
endif

# 目标可执行文件
TARGET = scheduler_optimizer

# 源文件
SOURCES = main.c graph_core.c csv_loader.c optimizer.c

# 对象文件
OBJECTS = $(SOURCES:.c=.o)

# 头文件
HEADERS = graph.h

# 默认目标
all: $(TARGET)

# 编译可执行文件
$(TARGET): $(OBJECTS)
	$(CC) $(OBJECTS) -o $@ $(LDFLAGS)

# 编译对象文件
%.o: %.c $(HEADERS)
	$(CC) $(CFLAGS) -c $< -o $@

# 带OpenMP支持的编译
openmp: 
	$(MAKE) OPENMP=1

# 调试版本
debug:
	$(MAKE) DEBUG=1

# 性能优化版本 
release:
	$(MAKE) CFLAGS="-Wall -Wextra -O3 -march=native -std=c99 -DNDEBUG"

# 清理生成文件
clean:
	rm -f $(OBJECTS) $(TARGET) test_basic test_basic.o
	rm -f *.txt *.csv gmon.out profile_report.txt

# 安装依赖（如果需要）
install-deps:
	# Ubuntu/Debian: sudo apt-get install gcc libomp-dev
	# CentOS/RHEL: sudo yum install gcc openmp-devel
	# macOS: brew install gcc libomp

# 编译基本测试程序
test_basic: test_basic.o graph_core.o csv_loader.o
	$(CC) test_basic.o graph_core.o csv_loader.o -o $@ $(LDFLAGS)

test_basic.o: test_basic.c $(HEADERS)
	$(CC) $(CFLAGS) -c $< -o $@

# 运行测试
test: $(TARGET)
	./$(TARGET)

# 运行基本功能测试
test-basic: test_basic
	./test_basic

# 基准测试
benchmark: $(TARGET)
	echo "=== 基准测试开始 ==="
	time ./$(TARGET)
	echo "=== 基准测试结束 ==="

# 内存检查（需要Valgrind）
memcheck: debug
	valgrind --leak-check=full --show-leak-kinds=all ./$(TARGET)

# 性能分析（需要gprof）
profile: CFLAGS += -pg
profile: LDFLAGS += -pg  
profile: $(TARGET)
	./$(TARGET)
	gprof $(TARGET) gmon.out > profile_report.txt

# 帮助信息
help:
	@echo "可用的make目标："
	@echo "  all       - 编译标准版本"
	@echo "  openmp    - 编译OpenMP并行版本"
	@echo "  debug     - 编译调试版本"
	@echo "  release   - 编译高性能优化版本"
	@echo "  clean     - 清理生成文件"
	@echo "  test      - 编译并运行测试"
	@echo "  benchmark - 运行基准测试"
	@echo "  memcheck  - 内存泄漏检查"
	@echo "  profile   - 性能分析"
	@echo ""
	@echo "使用示例："
	@echo "  make openmp    # 编译并行版本"
	@echo "  make test      # 运行测试"
	@echo "  ./scheduler_optimizer Conv_Case0_Nodes.csv Conv_Case0_Edges.csv"

# 伪目标声明
.PHONY: all clean test benchmark memcheck profile help install-deps openmp debug release
